package vsqlbuilder.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import vsqlbuilder.logic.postgresql.connection;
import vsqlbuilder.logic.sql.Query;

//TODO [low]: test reliability of using a page division of the table for very very large queries results.

//IMPORTANT!!!!!: this SqlRetrieve function must close connection after use, with this.DatabaseConnection.closeSQL();
//TODO [medium]: Try to fix the must close connection after use, with this.DatabaseConnection.closeSQL() of this class
public class SqlExecute extends JDialog {

	static final long serialVersionUID = 0L; //TODO [low]: temporary fix, must be change to correct one
	
	private SqlExecuteModel execModel = null;
	private JTable execTable;
	private connection DatabaseConnection;
	private JScrollPane tableScroll;

	public SqlExecute(JFrame owner, connection conn, Query query) {
		// DefaultTableModel execModel = new DefaultTableModel();
		super(owner, true);
		String sql;
		if (query.isReady()) {
			sql = query.GenerateSentence();
			System.out.println("DEBUG info SQL Sentence: "+sql);
		} else {
			// if the query object is not ready to generate sentence then do
			// default sentence
			sql = "select 'SELECT ANY COLUMN FROM TABLE PLEASE' from pg_database;";
			// TODO [medium]: search for a better way of explain this error to the user

		}
		this.setModal(true);
		setBackground(Color.WHITE);
		// Set Size
		Dimension fullscreen = Toolkit.getDefaultToolkit().getScreenSize();
		fullscreen.width = fullscreen.width - 100;
		fullscreen.height = fullscreen.height - 100;
		this.setBounds(50, 50, fullscreen.width, fullscreen.height);
		getContentPane().setPreferredSize(fullscreen);
		this.setDefaultCloseOperation(HIDE_ON_CLOSE);
		this.setTitle("SQL results");
		this.setAlwaysOnTop(true);

		this.DatabaseConnection = conn;
		if (SqlRetrieve(sql)) {
			execModel = new SqlExecuteModel(DatabaseConnection.resultsetDB);
			execTable = new JTable(execModel);
			tableScroll = new JScrollPane();
			tableScroll.setViewportView(execTable);
			tableScroll.setColumnHeaderView(execTable.getTableHeader());
			this.add(tableScroll);
		}
	}

	public boolean SqlRetrieve(String SQLsentence) {
		boolean value = false;
		// if the database connection data is set but is not open, then open it.
		if (!this.DatabaseConnection.isOpenConnection()
				&& this.DatabaseConnection.getPassword().length() > 0) {
			this.DatabaseConnection.openConnection();
		}
		// If connection is open then retrieve data
		if (this.DatabaseConnection.isOpenConnection()) {
			if (this.DatabaseConnection.execSQL(SQLsentence)) {
				value = true;
			}
		}
		return value;
	}

}
